#!/usr/bin/python
# -*- coding: utf-8 -*-
#/*
# *      Copyright (C) 2013 by Tolin
# *
# *  This Program is free software; you can redistribute it and/or modify
# *  it under the terms of the GNU General Public License as published by
# *  the Free Software Foundation; either version 2, or (at your option)
# *  any later version.
# *
# *  This Program is distributed in the hope that it will be useful,
# *  but WITHOUT ANY WARRANTY; without even the implied warranty of
# *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# *  GNU General Public License for more details.
# *
# *  You should have received a copy of the GNU General Public License
# *  along with this program; see the file COPYING.  If not, write to
# *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# *  http://www.gnu.org/copyleft/gpl.html
# */

import urllib2, re, httplib, xbmc, xbmcgui, xbmcplugin, cookielib, xbmcaddon, os, urllib, base64

icon = xbmc.translatePath(os.path.join(os.getcwd().replace(';', ''), 'icon.png'))
siteUrl = 'uletno.info'
httpSiteUrl = 'http://' + siteUrl

h = int(sys.argv[1])


def construct_request(params):
	return '%s?%s' % (sys.argv[0], urllib.urlencode(params))

def showMessage(heading, message, times = 50000):
	xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")'%(heading, message, times, icon))
	
def GET(url):
	try:
		print 'def GET(%s):'%url
		req = urllib2.Request(url)
		f = urllib2.urlopen(req)
		a = f.read()
		f.close()
		return a
	except:
		showMessage('Не могу открыть URL def GET', url)
		return None
	
def DEC(param):

    hash1 = ("Q","W","X","B","M","I","5","2","c","x","p","s","6","R","k","0","H","z","l","b","4","3","1","t","8","=");
    hash2 = ("y","a","V","9","L","w","n","i","u","v","Z","7","G","Y","m","J","D","d","T","g","f","o","N","U","e","q");


    for i in range(0, len(hash1)):
        rr1 = hash1[i]
        rr2 = hash2[i]

        param = param.replace(rr1, '--')
        param = param.replace(rr2, rr1)
        param = param.replace('--', rr2)
	
    
    param = base64.b64decode(param)
    
    return param


def ROOT():

        name='Фильмы TOP List'
        li = xbmcgui.ListItem(name)
        url = sys.argv[0] + '?mode=TOP_List'
        xbmcplugin.addDirectoryItem(h, url, li, True)
        
	name='Все Фильмы'
        li = xbmcgui.ListItem(name)
        url = sys.argv[0] + '?mode=ALL_List'+'&url=%s'%urllib.quote_plus(httpSiteUrl)
        xbmcplugin.addDirectoryItem(h, url, li, True)
	
	name='Жанры'
        li = xbmcgui.ListItem(name)
        url = sys.argv[0] + '?mode=genre'
        xbmcplugin.addDirectoryItem(h, url, li, True)
        	
#	name='Поиск'
#        li = xbmcgui.ListItem(name)
#        url = sys.argv[0] + '?mode=search'
#        xbmcplugin.addDirectoryItem(h, url, li, True)
        		
	xbmcplugin.endOfDirectory(h)




def TOP_List():

	wurl = httpSiteUrl
	http = GET(wurl)
	if http == None: return False
	r1 = re.compile('<div class="list-items bwrbs">(.*?)</div><br />',re.S).findall(http)
	r2 = re.compile('<li><div class="stitle"><h2>(.*?)</h2></div><span class="poster"><a href="(.*?)" title=".*?"><img src="(.*?)" alt=".*?" /></a></span><div class="shview">(.*?)</div></li>',re.S).findall(r1[0])
	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов name,link')
		return False
	for name, href, img, vv in r2:
		vv = ' [COLOR ffDEB887]%s[/COLOR]'%(vv)
		img= httpSiteUrl + img
#		showMessage('img',img)
		i = xbmcgui.ListItem(unicode(name + '   ' + vv, "cp1251"), iconImage=img, thumbnailImage=img)
		u  = sys.argv[0] + '?mode=PLAY1'
		u += '&url=%s'%urllib.quote_plus(href)
		xbmcplugin.addDirectoryItem(h, u, i, True)
		
    	xbmcplugin.endOfDirectory(h)

def ALL_List(params):
	
	http = GET(urllib.unquote_plus(params['url']))
	if http == None: return False
	
#	wurl = httpSiteUrl
#	http = GET(wurl)
	if http == None: return False
	r1 = re.compile('<!-- frontpage page content -->(.*?)<!-- //frontpage page content -->',re.S).findall(http)

	r2 = re.compile('<li><div class="stitle"><h2>(.*?)</h2></div><span class="poster"><a href="(.*?)" title=".*?"><img src="(.*?)" alt=".*?" /></a></span>\s*<div class="shview">(.*?)</div></li>',re.S).findall(r1[0])
		
	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов name,link')
		return False
	for name, href, img, vv in r2:
		vv = ' [COLOR ffDEB887]%s[/COLOR]'%(vv)
		img= httpSiteUrl + img
#		showMessage('img',img)
		i = xbmcgui.ListItem(unicode(name + '   ' + vv, "cp1251"), iconImage=img, thumbnailImage=img)
		u  = sys.argv[0] + '?mode=PLAY1'
		u += '&url=%s'%urllib.quote_plus(href)
		xbmcplugin.addDirectoryItem(h, u, i, True)
		
	try:
		rp = re.compile('<div class="pagination">(.*?)</div>',re.S).findall(http)
		rp2 = re.compile('<a href="(.*?)">(.*?)</a>').findall(rp[0])
		for href, nr in rp2:
			u = sys.argv[0] + '?mode=ALL_List'
			u += '&url=%s'%urllib.quote_plus(href)
#			rPN = '[B][COLOR yellow]%s[/COLOR][/B]' % rPN
			i = xbmcgui.ListItem('[ Страница %s ]'%nr)
			xbmcplugin.addDirectoryItem(h, u, i, True)
	except:
		pass
		
    	xbmcplugin.endOfDirectory(h)

def genre():
	wurl = httpSiteUrl
	http = GET(wurl)
	if http == None: return False
	r1 = re.compile('<ul class="menu">(.*?)</ul>',re.S).findall(http)
	r2 = re.compile('<li><a href="(.*?)">(.*?)</a>',re.S).findall(r1[0])
	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов id,name,link,numberOfMovies')
		return False
	for href, name in r2:
		i = xbmcgui.ListItem(unicode(name, "cp1251"), iconImage=icon, thumbnailImage=icon)
#		i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
		u  = sys.argv[0] + '?mode=ALL_List'
		u += '&url=%s'%urllib.quote_plus(httpSiteUrl + href)
		u += '&name=%s'%urllib.quote_plus(name)
		xbmcplugin.addDirectoryItem(h, u, i, True)
	
	xbmcplugin.endOfDirectory(h)
	
	
def search():
	
	skbd = xbmc.Keyboard()
	skbd.setHeading('Название фильма или часть названия')
	skbd.doModal()

	SearchString = skbd.getText(0)
	url = httpSiteUrl+'/do=search&subaction=search&story='+ SearchString

	http = GET(url)
	if http == None: return False
	r1 = re.compile('<!-- frontpage page content -->(.*?)<!-- //frontpage page content -->',re.S).findall(http)

	r2 = re.compile('<li><div class="stitle"><h2>(.*?)</h2></div><span class="poster"><a href="(.*?)" title=".*?"><img src="(.*?)" alt=".*?" /></a></span>\s*<div class="shview">(.*?)</div></li>',re.S).findall(r1[0])
		
	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов name,link')
		return False
	for name, href, img, vv in r2:
		vv = ' [COLOR ffDEB887]%s[/COLOR]'%(vv)
		img= httpSiteUrl + img
#		showMessage('img',img)
		i = xbmcgui.ListItem(unicode(name + '   ' + vv, "cp1251"), iconImage=img, thumbnailImage=img)
		u  = sys.argv[0] + '?mode=PLAY1'
		u += '&url=%s'%urllib.quote_plus(href)
		xbmcplugin.addDirectoryItem(h, u, i, True)
	xbmcplugin.endOfDirectory(h)
	


def OPEN_MOVIES(params):
	http = GET(urllib.unquote_plus(params['url']))
	if http == None: return False
	
	r1 = re.compile('<div class="item-trailer">(.*?)<div class="clear"></div>',re.S).findall(http)
	r2 = re.compile('<td width="60%" class="roltitle">(.*?)\s*<a href="(.*?)"></a>',re.S).findall(r1[0])
	r3 = re.compile('><img src="(.*?)" width="120"',re.S).findall(r1[0])
	#r4 = re.compile('Посмотрели:(.*?)</td>',re.S).findall(r1[0])
	
	rr1 = re.compile('<td class="newnews"(.*?)<td width="4" align="right" valign="top">',re.S).findall(r1[0])
	rt1 = re.compile('<table class="storyinfo"(.*?)<div class="quote">',re.S).findall(r1[0])
	tt1 = re.compile('<div class="quote">(.*?)<table width="100%" border="0" cellspacing="0" cellpadding="0">',re.S).findall(r1[0])
		
	rr=0

	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов id,name,link,numberOfMovies')
		return False
	for name, href in r2:
		name = name[:-22]
		
			
		tt2 = re.compile('">(.*?)</span></td></tr>').findall(tt1[rr])
		if len(tt2) == 0: tt2 = ' '
		tt2 = tt2[0]
		rr2 = re.compile(':(.*?)</td>').findall(rr1[rr])
		rr2 = rr2[0]
		rt2 = re.compile('">(.*?)</span>').findall(rt1[rr])
		
		if len(rt2) == 0: rt2 = '0'
		rt2 = rt2[0]
		
		rt2 = '  [COLOR ff8B0000]IMDB:[/COLOR] [COLOR ffFF0000]%s[/COLOR]  /  [COLOR ffDEB887]%s[/COLOR]    [COLOR ffFF7F24]%s[/COLOR]'% (rt2, rr2, tt2)
		
		name = name + rt2
		rr=rr+1
		i = xbmcgui.ListItem(unicode(name, "cp1251"), iconImage=img, thumbnailImage=img)
		u  = sys.argv[0] + '?mode=PLAY1'
		u += '&url=%s'%urllib.quote_plus(href)
		i.setProperty('IsPlayable', 'true')
		xbmcplugin.addDirectoryItem(h, u, i, True)
	try:
		rp = re.compile('<div class="navigation"(.*?)</td>', re.DOTALL).findall(http)[0]
		rp2 = re.compile('<a href="(.*?)">(.*?)</a>').findall(rp)
		for href, nr in rp2:
			u = sys.argv[0] + '?mode=OPEN_MOVIES'
			u += '&url=%s'%urllib.quote_plus(href)
#			rPN = '[B][COLOR yellow]%s[/COLOR][/B]' % rPN
			i = xbmcgui.ListItem('[ Страница %s ]'%nr)
			xbmcplugin.addDirectoryItem(h, u, i, True)
	except:
		pass	
		
		
	xbmcplugin.endOfDirectory(h)
	
	
def PLAY1(params):
	http = GET(urllib.unquote_plus(params['url']))
#	showMessage('url in Play', params['url'])
	if http == None: return False
	rows1 = re.compile('"file":"(.*?)"').findall(http)
	rows1 = DEC(rows1[0])
#	showMessage('rows1', rows1)
#	r1 = rows1[0]
	if len(rows1) == 0:
		showMessage('УпС', 'Нет видеофайла')
		return False
	xbmc.Player().play(rows1)




def get_params(paramstring):
	param=[]
	if len(paramstring)>=2:
		params=paramstring
		cleanedparams=params.replace('?','')
		if (params[len(params)-1]=='/'):
			params=params[0:len(params)-2]
		pairsofparams=cleanedparams.split('&')
		param={}
		for i in range(len(pairsofparams)):
			splitparams={}
			splitparams=pairsofparams[i].split('=')
			if (len(splitparams))==2:
				param[splitparams[0]]=splitparams[1]
	return param

params=get_params(sys.argv[2])


mode = None

try:
	mode = urllib.unquote_plus(params['mode'])
except:
	ROOT()

if mode == 'ROOT': ROOT()
if mode == 'TOP_List': TOP_List()
if mode == 'genre': genre()
if mode == 'search': search()
if mode == 'ALL_List': ALL_List(params)
if mode == 'OPEN_MOVIES': OPEN_MOVIES(params)
if mode == 'PLAY1': PLAY1(params)


